import { defineStore } from 'pinia';
import { ref } from 'vue'; // 用户模块
import { userGetInfoService } from '../../api/user';

// token 管理
export const useUserStore = defineStore('big-user', () => {
  const token = ref('');

  //在登录页面登录后设置token
  const setToken = (newToken) => {
    token.value = newToken;
  };


  const user = ref({});

  /**
{
  "avatarUrl": "https://img2.baidu.com/it/u=975062466,2873258082&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500",
  "nickName": "焰的rpg",
  "userId": 48,
  "userName": "E02118855",
  "userRole": {
    "code": 1,
    "desc": "admin"
  }
}

   */
  const getUser = async () => {
    const res = await userGetInfoService(); // 请求获取数据
    // console.log('Pinia模块的userGetInfoService', res);
    setUser(res.data) // 存储用户数据
  };

  const setUser = (obj) => {
    user.value = obj; // 设置用户信息
  };
  const clearUser = () => {
    console.log('Pinia模块的clearUser');

    setUser({}); // 清空用户信息
    setToken(''); // 清空 token
    // 可选：手动清除 localStorage（确保完全清理）
    // localStorage.removeItem('big-user');
     // 清除所有端口的本地存储
     ['http://localhost:8999', 'http://localhost:9999'].forEach(origin => {
      localStorage.removeItem(`persist:big-user@${origin}`);
      localStorage.removeItem(`big-user`);
    });

  }

  return {
    token,
    setToken,
    user,
    getUser,
    setUser, 
    clearUser,
  };
},
  {
    persist: {
      paths: ['token', 'user'],
    }
  }
);
